<template>
  <view class="container-release">
    <navbar :config="config" backColor="#fff"></navbar>
    <view class="main">
      <u-form :model="form" ref="formRef" label-width="150">
        <u-form-item label="所属分类" prop="classifyLabel">
          <u-input v-model="form.classifyLabel" type="select" placeholder="请选择" placeholder-style="text-align: right"
            @click="classifyShow = true" />
        </u-form-item>
        <u-form-item label="所属类型" prop="typeLabel">
          <u-input v-model="form.typeLabel" type="select" placeholder="请选择" placeholder-style="text-align: right"
            @click="typeShow = true" />
        </u-form-item>
        <u-form-item label="名称" prop="name">
          <u-input v-model="form.name" placeholder="请输入" placeholder-style="text-align: right" />
        </u-form-item>
        <u-form-item label="售价（￥）" prop="price">
          <u-input v-model="form.price" placeholder="请输入" placeholder-style="text-align: right" />
        </u-form-item>
        <u-form-item label="原价（￥）" prop="original_price">
          <u-input v-model="form.original_price" placeholder="请输入" placeholder-style="text-align: right" />
        </u-form-item>
        <u-form-item label="图片" label-position="top" prop="img">
          <!-- <u-upload :action="action" @on-success="onSuccessImg"
            :file-list="form.img" max-count="1"></u-upload> -->
          <uploadImg imgCount="1" uploadImgCount="1" :imgArr="img" :type="upimgtype" url="" @result="resultImg">
          </uploadImg>
        </u-form-item>
        <u-form-item label="图文详情" label-position="top" class="content-box" prop="details">
          <u-input v-model="form.details" maxlength="600" type="textarea" placeholder="请输入" @input="detailsChange" />
          <view class="content"><text>{{enterNum}}</text>/600</view>
        </u-form-item>
        <u-form-item>
          <!-- <u-upload :action="action" @on-success="onSuccessImgs" :file-list="form.detailsImages" max-count="6">
          </u-upload> -->
          <uploadImg imgCount="6" uploadImgCount="6" :imgArr="detailsImages" :type="upimgtype" url=""
            @result="resultImgs"></uploadImg>
        </u-form-item>
      </u-form>
    </view>
    <u-select v-model="classifyShow" label-name="name" value-name="id" :list="classifyList"
      :default-value="[classifyIndex]" @confirm="classifyConfirm"></u-select>
    <u-select v-model="typeShow" label-name="name" value-name="id" :list="typeList" :default-value="[typeIndex]"
      @confirm="typeConfirm"></u-select>
    <view class="footer">
      <view class="online-btn btn" @click="submit(0)">保存</view>
      <view class="btn" @click="submit(1)">提交发布</view>
    </view>
  </view>
</template>

<script>
  import uploadImg from "../../../components/uploadImg/imgUpload.vue"
  export default {
    components: {
      uploadImg
    },
    data() {
      return {
        config: {
          back: true,
          title: '发布商品',
          color: '#fff',
          backgroundColor: [1, "#FF721B"],
          statusBarFontColor: '#1A1A1A',
          leftSlot: true
        },
        shopId: '',
        form: {},
        action: this.$mConfig.baseUrl + '/sys/oss/upload',
        detailsImages: [],
        upimgtype: 'other',
        img: [],
        classifyShow: false,
        classifyList: [],
        classifyIndex: 0,
        typeList: [{
            name: '商品',
            id: 0
          },
          {
            name: '服务',
            id: 1
          }
        ],
        typeIndex: 0,
        typeShow: false,
        enterNum: 0,
        rules: {
          classifyLabel: [{
            required: true,
            message: '所属分类不能为空',
            trigger: ['change', 'blur'],
          }],
          typeLabel: [{
            required: true,
            message: '所属类型不能为空',
            trigger: ['change', 'blur'],
          }],
          name: [{
            required: true,
            message: '名称不能为空',
            trigger: ['change', 'blur'],
          }],
          price: [{
            required: true,
            message: '售价不能为空',
            trigger: ['change', 'blur'],
          }, {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              if (this.$u.test.chinese(value)) {
                return callback(new Error('请输入数字类型'));
              } else if (!this.$u.test.amount(value)) {
                return callback(new Error('最多两位小数'));
              }
              callback()
            },
            // message: '最多两位小数',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          }],
          original_price: [{
            required: true,
            message: '原价不能为空',
            trigger: ['change', 'blur'],
          }, {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              if (this.$u.test.chinese(value)) {
                return callback(new Error('请输入数字类型'));
              } else if (!this.$u.test.amount(value)) {
                return callback(new Error('最多两位小数'));
              }
              callback()
            },
            // message: '最多两位小数',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          }],
          img: [{
            required: true,
            message: '图片不能为空',
            trigger: ['change', 'blur'],
          }],
          details: [{
            required: true,
            message: '详情不能为空',
            trigger: ['change', 'blur'],
          }],
        },
      }
    },
    onLoad(options) {
      if (options.goodsId) {
        this.goodsId = options.goodsId
        this.$nextTick(() => {
          this.getGoodsDetail(options.goodsId)
        })
      }
      this.getClassifylist()
    },
    onReady() {
      this.$refs.formRef.setRules(this.rules);
    },
    methods: {
      // 获取分类列表
      getClassifylist() {
        this.$http.get('/offlinetype/goods/my_list', {
          isGoods: 1,
        }).then(res => {
          if (res.code == 200) {
            if (res.list.length > 0) {
              this.classifyList = res.list
            }
          }
        })
      },
      getGoodsDetail(id) {
        this.$http.get(`/offline/goods/info/${id}`, {
          id: id
        }).then(res => {
          if (res.code == 200) {
            this.form = res.data
            this.form.price = res.data.price.toString()
            this.form.original_price = res.data.original_price.toString()
            this.img = res.data.img.split()
            this.detailsImages = res.data.details_images
            this.enterNum = res.data.details.length
            this.getType(res.data.type_id, 'type_id')
            this.getType(res.data.type, 'type')
          }
        })
      },
      getType(id, str) {
        let list = str == 'type' ? this.typeList : this.classifyList
        for (let item of list) {
          if (item.id == id) {
            if (str == 'type') {
              return this.form.typeLabel = item.name
            } else {
              return this.form.classifyLabel = item.name
            }
          }
        }
      },
      classifyConfirm(e) {
        if (e.length > 0) {
          this.form.type_id = e[0].value
          this.form.classifyLabel = e[0].label
          for (let i in this.classifyList) {
            if (this.classifyList[i].id == e[0].value) {
              this.classifyIndex = Number(i)
              return false
            }
          }
        }
      },
      typeConfirm(e) {
        if (e.length > 0) {
          this.form.type = e[0].value
          this.form.typeLabel = e[0].label
          for (let i in this.typeList) {
            if (this.typeList[i].id == e[0].value) {
              this.typeIndex = Number(i)
              return false
            }
          }
        }
      },
      detailsChange(e) {
        if (e) {
          this.enterNum = e.length
        }
      },
      resultImg(e) {
        this.imgs = e
        this.form.img = e[0]
      },
      resultImgs(e) {
        this.detailsImages = e
        this.form.details_images = e
      },
      submit(type) {
        this.$refs.formRef.validate(valid => {
          if (valid) {
            let url = '/offline/goods/save'
            let method = 'post'
            if (this.goodsId) {
              url = '/offline/goods/update'
              method = 'put'
            }
            this.$http[method](url, {
              ...this.form,
              is_release: type
            }).then(res => {
              if (res.code == 200) {
                this.$mUtil.toast(type == 0 ? '保存成功' : '发布成功')
                setTimeout(() => {
                  uni.navigateBack()
                }, 1000)
              }
            })
          } else {
            console.log('验证失败');
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container-release {

    .main {
      padding: 20rpx 30rpx 200rpx;

      /deep/ .u-form {
        .u-input__right-icon__item {
          display: flex;
          align-items: center;
        }

        .uicon-arrow-down-fill::before {
          width: 32rpx;
          height: 32rpx;
          content: '';
          background: url('https://zhongyi-shop.oss-cn-beijing.aliyuncs.com/songhe/weixin/static/personal/select-icon.png') no-repeat;
          background-size: 100% 100%;
        }

        .content-box {
          .u-form-item--right__content__slot {
            flex-direction: column;

            .u-input {
              width: 100%;
            }

            .content {
              width: 100%;
              text-align: right;
            }
          }
        }

        .content {
          font-size: 24rpx;
          font-family: PingFang SC, PingFang SC-Regular;
          font-weight: 400;
          color: #808080;

          text {
            color: #EF3124;
          }
        }
      }
    }

    .footer {
      width: 100%;
      padding: 30rpx 60rpx;
      position: fixed;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      z-index: 99;

      .btn {
        width: 298rpx;
        color: #fff;
        text-align: center;
        line-height: 85rpx;
        border: 1rpx solid #FF721B;
        border-radius: 44rpx;
        background-color: #FF721B;
        font-size: 28rpx;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
      }

      .online-btn {
        color: #FF721B;
        border: 1rpx solid #FF721B;
        background-color: #e7eefc;
      }
    }
  }
</style>
